package com.wanyu.video.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class BIOServer {

    public static void main(String[] args) throws IOException {

        // 简单demo编写直接使用，实际编程中不建议这么创建线程池
        ExecutorService executorService = Executors.newCachedThreadPool();

        // 1.创建一个ServerSocket并监听6666端口
        ServerSocket serverSocket = new ServerSocket(6666);
        System.out.println("服务端已启动并监听6666端口");

        while(true){
            // 主线程会一直循环调用，当没有新的连接的时候，就会被阻塞，下面代码可以验证
            System.out.println("  主线程 waiting connect--------  " + Thread.currentThread().getName());
            // 等待客户端连接
            Socket socket = serverSocket.accept();
            System.out.println("成功连接到一个客户端");
            executorService.execute(() -> handler(socket));
        }
    }

    public static void handler(Socket socket){

        System.out.println("当前线程信息： id = " + Thread.currentThread().getId()  + " 名称 = " + Thread.currentThread().getName());
        byte[] bytes = new byte[1024];
        try {
            InputStream inputStream = socket.getInputStream();
            while(true){

                // 创建的线程会被read阻塞，除非读取到东西
                System.out.println("线程初次执行或者完成读取后，阻塞在此等待客户端发送消息----------- " + Thread.currentThread().getName());
                int read = inputStream.read(bytes);
                if(read != -1){
                    System.out.println(new String(bytes, 0, read));
                }else {
                    break;
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            System.out.println("关闭socket");
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
